package com.googlecode.tidej.client.project;

import java.io.IOException;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.googlecode.tidej.client.Dialog;
import com.googlecode.tidej.client.TidejController;
import com.googlecode.tidej.client.PersistentState;


public class OpenProjectDialog extends Dialog {
  ListBox projectListBox = new ListBox();
  Button loadButton;
  TidejController controller;
  PersistentState projects;
  FlowPanel mainPanel = new FlowPanel();

  public OpenProjectDialog(final TidejController controller) {
    super("Open Project");
    this.controller = controller;
    FlexTable table = new FlexTable();
    
    table.setText(0, 0, "Project name:");
    table.setWidget(0, 1, projectListBox);
    loadButton = new Button("Load");
    loadButton.addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        String name = projectListBox.getItemText(
            projectListBox.getSelectedIndex());
        try {
          projects.setLastOpened(name);
          projects.save();
        } catch (IOException e) {
          Window.alert("Saving projects failed: " + e.getMessage());
        }
        controller.openProject(name, null);
        hide();
      }
    });
    addButton(loadButton);
    
    getContentPanel().add(table);
  }
  
  public void run() {
    projects = PersistentState.load();
    projectListBox.clear();
    for (String name: ProjectManager.getProjectNames()) {
      projectListBox.addItem(name);
    }
    loadButton.setEnabled(projectListBox.getItemCount() > 0);
    show();
    center();
  }
}
